from django.shortcuts import render,get_object_or_404
from .models import Post,Category,Comment,Brief
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from taggit.models import Tag
from  .froms import CommentForm,EmailPostForm
import markdown
import re
from django.core.mail import send_mail,EmailMultiAlternatives
from django.utils.text import slugify
from markdown.extensions.toc import TocExtension
# Create your views here.
def post_base(posts,around_count):
    current_page = posts.number  # 获取当前页码
    num_pages = posts.paginator.num_pages  # 总共有多少页
    left_has_more = False
    right_has_more = False
    if current_page <= around_count + 2:
        left_pages = range(1, current_page)  #
    else:
        left_has_more = True
        left_pages = range(current_page - around_count, current_page)
    if current_page >= num_pages - around_count - 1:
        right_pages = range(current_page + 1, num_pages + 1)
    else:
        right_has_more = True
        right_pages = range(current_page + 1, current_page + around_count + 1)
    return [left_pages,right_pages,current_page,left_has_more,right_has_more,num_pages]

#首页
def post_index(request,around_count=3):
    categorys = Category.objects.all()
    object_list=Post.published.all()
    paginator=Paginator(object_list,around_count)#每页3篇
    page=request.GET.get('page')#获取当前页面号
    try:
        posts=paginator.page(page)
    except PageNotAnInteger:
        #所给页面不是整数，提交第一页
        posts=paginator.page(1)#获取所需的页面对象
    except EmptyPage:
        #页面超出范围提交最后一页
        posts=paginator.page(paginator.num_pages)
    base=post_base(posts,around_count)
    page_url = request.path_info
    return render(request,'blog/index.html',{'posts':posts,
                                             'page_url': page_url,
                                             'categorys':categorys,
                                             'left_pages': base[0],  # 左边页数
                                             'right_pages': base[1],  # 右边页数
                                             'current_page': base[2],  # 当前页码
                                             'left_has_more': base[3],  # 左是否有页码
                                             'right_has_more': base[4],  # 右是否有页码
                                             'num_pages': base[5]  # 总共多少页
                                             })

#博客
def post_full_width(request,around_count=3):
    object_list = Post.published.all()
    paginator = Paginator(object_list, around_count)  # 每页3篇
    page = request.GET.get('page')  # 获取当前页面号
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # 所给页面不是整数，提交第一页
        posts = paginator.page(1)  # 获取所需的页面对象
    except EmptyPage:
        # 页面超出范围提交最后一页
        posts = paginator.page(paginator.num_pages)
    base = post_base(posts, around_count)
    return render(request, 'blog/full-width.html', {'posts': posts,
                                               'left_pages': base[0],  # 左边页数
                                               'right_pages': base[1],  # 右边页数
                                               'current_page': base[2],  # 当前页码
                                               'left_has_more': base[3],  # 左是否有页码
                                               'right_has_more': base[4],  # 右是否有页码
                                               'num_pages': base[5]  # 总共多少页
                                               })

#关于
def post_about(request):
    brief=Brief.objects.all().first()
    if brief:
        img=brief.post_img
        letter=brief.post_letter
    else:
        img='#'
        letter='~~~~~~博主有点赖~~~~~~'
    return render(request,'blog/about.html',{'img':img,'letter':letter})

#联系博主
def post_contact(request):
    sent = False
    if request.method == 'POST':
        # 通过request.POST提交过来的数据生成一个实例
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # is_valid()对引入的数据进行验证
            cd = form.cleaned_data
            sent = True  # 帖子发送后为True
            # # 邮件标题
            # subject = '{}'.format(cd['theme'])
            # # 邮件正文
            # message = '<h2>游客 <{}> 通过邮件联系了你： </h2>\n\n\t<b>"{}"</b>游客留言：{}'.format(cd['send_email'],cd['sender'],cd['message_board'])
            # sender = '博客来访<15027287198@163.com>'# 发件人
            # receiver = ['15027287198@163.com']  # 收件人
            # send_mail(subject, message, sender, receiver)
            # sent = True  # 帖子发送后为True

            #发送html邮件
            subject = '{}'.format(cd['theme'])
            text_content='<{}>博客有人留言：\n\n\t"{}"游客留言：{}'.format(cd['send_email'],cd['sender'],cd['message_board'])
            html_content='<h2>游客 <{}> 通过邮件联系了你： </h2>\n\n<b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"{}"</b>游客留言：{}'.format(cd['send_email'],cd['sender'],cd['message_board'])
            from_email = '博客来访<15027287198@163.com>'  # 发件人
            to = ['15027287198@163.com']  # 收件人
            msg= EmailMultiAlternatives(subject,text_content,from_email,to)
            msg.attach_alternative(html_content,"text/html")
            msg.send()
    return render(request,'blog/contact.html',{'sent':sent})

#帖子详细内容
def post_single(request,year,month,day,post):
    #采用get_object_or_404()快捷方式检索期望的帖子，对象不存在，会抛出HTTP404异常
    #检索到会返回，检索到的对象
    categorys = Category.objects.all()
    post = get_object_or_404(Post,slug=post,
                                   status='published',
                                    publish__year=year,
                                    publish__month=month,
                                    publish__day=day,
                             )
    # 阅读量 +1
    post.increase_views()
    # 获取活跃的评论
    comments = post.comments.filter(active=True)
    new_comment = None
    if request.method == 'POST':
    # 实例化帖子
        comment_form=CommentForm(data=request.POST)
        if comment_form.is_valid():
            # 调用save方法创建创建表单所链接的模型实例，并保存到数据库中
            # 如采用commit=False，表示对其加以调用，将会创建模型实例，但不会将其保存到数据库中
            # 需要在保存前进行修改，就十分有用
            new_comment = comment_form.save(commit=False)
            # 将当前帖子设置到创建的评论中
            new_comment.post = post
            # 保存评论到数据库
            new_comment.save()
    else:
        comment_form = CommentForm()
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        TocExtension(slugify=slugify),
    ])
    post.body = md.convert(post.body)
    #帖子目录
    m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>', md.toc, re.S)
    post.toc = m.group(1)
    path = request.path_info
    return render(request,'blog/single.html',{'post':post,'categorys':categorys,
                                              'comments': comments,
                                              'new_comment': new_comment,
                                              'comment_form': comment_form,
                                              'path': path
                                              })


#归档
def post_pigeonhole(request,year,month,around_count=3):
    categorys = Category.objects.all()
    object_list = Post.objects.filter(created__year=year,created__month=month).order_by('-created')
    paginator=Paginator(object_list,around_count)#每页3篇
    page=request.GET.get('page')#获取当前页面号
    try:
        posts=paginator.page(page)
    except PageNotAnInteger:
        #所给页面不是整数，提交第一页
        posts=paginator.page(1)#获取所需的页面对象
    except EmptyPage:
        #页面超出范围提交最后一页
        posts=paginator.page(paginator.num_pages)
    base = post_base(posts, around_count)
    page_url = request.path_info
    return render(request, 'blog/index.html', {'posts': posts,
                                               'categorys':categorys,
                                               'page_url':page_url,
                                               'left_pages': base[0],  # 左边页数
                                               'right_pages': base[1],  # 右边页数
                                               'current_page': base[2],  # 当前页码
                                               'left_has_more': base[3],  # 左是否有页码
                                               'right_has_more': base[4],  # 右是否有页码
                                               'num_pages': base[5]  # 总共多少页
                                               })

#分类
def post_category(request,title,around_count=3):
    categorys = Category.objects.all()
    object_list=Category.objects.get(class_name=title).posts_category.all()
    paginator = Paginator(object_list, around_count)  # 每页3篇
    page = request.GET.get('page')  # 获取当前页面号
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # 所给页面不是整数，提交第一页
        posts = paginator.page(1)  # 获取所需的页面对象
    except EmptyPage:
        # 页面超出范围提交最后一页
        posts = paginator.page(paginator.num_pages)
    base = post_base(posts, around_count)
    page_url = request.path_info
    return render(request, 'blog/index.html', {'posts': posts,
                                               'categorys':categorys,
                                               'page_url': page_url,
                                               'left_pages': base[0],  # 左边页数
                                               'right_pages': base[1],  # 右边页数
                                               'current_page': base[2],  # 当前页码
                                               'left_has_more': base[3],  # 左是否有页码
                                               'right_has_more': base[4],  # 右是否有页码
                                               'num_pages': base[5]  # 总共多少页
                                               })
#标签页面
from  django.http import HttpResponse
def post_tags(request,title,around_count=3):
    categorys = Category.objects.all()
    tag = get_object_or_404(Tag, name=title)
    object_list = Post.objects.filter(tags__in=[tag])
    paginator = Paginator(object_list, around_count)  # 每页3篇
    page = request.GET.get('page')  # 获取当前页面号
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # 所给页面不是整数，提交第一页
        posts = paginator.page(1)  # 获取所需的页面对象
    except EmptyPage:
        # 页面超出范围提交最后一页
        posts = paginator.page(paginator.num_pages)
    base = post_base(posts, around_count)
    return render(request, 'blog/index.html', {'posts': posts,
                                               'categorys':categorys,
                                               'left_pages': base[0],  # 左边页数
                                               'right_pages': base[1],  # 右边页数
                                               'current_page': base[2],  # 当前页码
                                               'left_has_more': base[3],  # 左是否有页码
                                               'right_has_more': base[4],  # 右是否有页码
                                               'num_pages': base[5]  # 总共多少页
                                               })



